package free.order.security.action;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import free.order.common.action.BaseAction;
import free.order.security.entity.Role;
import free.order.security.entity.User;
import free.order.security.service.SecurityService;

public class LoginAction extends BaseAction {
	
	private static final long serialVersionUID = 6270585511897283525L;
	
    private static final Log log = LogFactory.getLog(LoginAction.class);
	
	private String loginID = null;
	
	private String loginPW = null;
	
	private SecurityService securityServ = null;
	
	public String getLoginID() {
		return loginID;
	}

	public void setLoginID(String loginID) {
		this.loginID = loginID;
	}

	public String getLoginPW() {
		return loginPW;
	}

	public void setLoginPW(String loginPW) {
		this.loginPW = loginPW;
	}

	public SecurityService getSecurityServ() {
		return securityServ;
	}

	public void setSecurityServ(SecurityService securityServ) {
		this.securityServ = securityServ;
	}

	public String doLogin(){
		boolean loginSuccess = false;
		System.out.println("loginID=" + this.loginID);
		System.out.println("loginPW=" + this.loginPW);		
		try
        {
            User user = securityServ.getUserByLoginID(loginID);
            if (user == null)
            {
                setError("用户不存在或已经被删除！");
            }
            else if(!user.getPasswd().equals(loginPW))
            {
                setError("用户密码不正确，请重新输入！");
            }
            else
            {
                //如果用户已经登录，让已经登录的用户超时
//                if (mLoginedUsers.containsKey(userAccount))
//                {
//                    HttpSession session = mLoginedUsers.remove(userAccount);
//                    session.setAttribute(Constant.USER, null);
//                    session.invalidate();
//                }
//                getSession().setAttribute(Constant.USER, user);
//                mLoginedUsers.put(userAccount, getSession());
                loginSuccess = true;
            }
        }
        catch(Exception e)
        {
            log.error("登陆失败！", e);
            setError("数据库连接失败！");
        }
        
        if (loginSuccess)
        {
            return "loginSuccess";
        }
        else
        {
            return "loginFailure";
        }
	}
	
	//for register page
	
	private List<Role> allRoles;
	
	public List<Role> getAllRoles() {
		return allRoles;
	}
	
	public String doRegister(){
		allRoles = this.securityServ.getAllRoles();
		return "register";
	}
}
